from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from cart import models,cartser
from utils.authorization import MyAuthentication
# Create your views here.

# 添加商品到购物车
class AddCartView(APIView):
    authentication_classes = [MyAuthentication,]
    def post(self,request):
        user=request.data.get('user',"")
        course=request.data.get('course',"")
        if user and course:
            info=models.CartModel.objects.filter(user=user,course=course).first()
            if info:
                return Response({'msg':"购物车中已存在"})
            else:
                ser=cartser.CartSerializer(data=request.data)
                if ser.is_valid():
                    ser.save()
                    return Response({'msg':"添加成功"})
                else:
                    return Response({"msg": ser.errors})
        else:
            return Response({'detail':"请传入必要参数",})

class CarList(APIView):
    authentication_classes = [MyAuthentication,]
    def get(self,request):
        user=request.query_params.get('user',"")
        if user=="":
            return Response({'detail': "请传入必要参数", })
        cart=models.CartModel.objects.filter(user=user)
        ser=cartser.CartSerializer(cart,many=True)
        return Response({'msg':"查询成功", 'data':ser.data})

class ChangeOne(APIView):
    authentication_classes = [MyAuthentication,]
    def put(self,request):
        id=request.data.get("id","")
        if id=="":
            return Response({'detail':"请传入必要参数",})
        cart=models.CartModel.objects.filter(id=id).first()
        cart.select=not cart.select
        cart.save()
        return Response({"msg":"修改成功"})

class ChangAll(APIView):
    authentication_classes = [MyAuthentication,]
    def put(self,request):
        user=request.data.get('user',"")
        select=request.data.get("selected","")
        if user=="":
            return Response({'detail':"请传入必要参数",})
        cart=models.CartModel.objects.filter(user=user)
        for i in cart:
            i.select=select
            i.save()
        return Response({'msg':'修改成功'})
class Delete(APIView):
    authentication_classes = [MyAuthentication,]
    def delete(self,request):
        id=request.query_params.get("course_id","")
        if id=="":
            return Response({'detail':"请传入必要参数",})
        cart=models.CartModel.objects.filter(id=id).first()
        cart.delete()
        return Response({'msg':'删除成功'})